import React, { useState, useEffect, useCallback } from 'react';
import { Layout, Menu, Typography, Avatar, Dropdown, Badge, notification, Divider, Space, Tooltip, message } from 'antd';
import {
  MessageOutlined,
  DashboardOutlined,
  TeamOutlined,
  SettingOutlined,
  UserOutlined,
  LogoutOutlined,
  BellOutlined,
  LinkOutlined,
  FileOutlined,
  WechatOutlined,
  InboxOutlined,
  ArrowLeftOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import socketService from '../../services/socket';
import ContactSearch from '../ContactSearch';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;

const MainLayout = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [notifications, setNotifications] = useState([]);
  const { user, logout } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  // 显示敏感内容通知
  const showSensitiveContentNotification = useCallback((data) => {
    notification.warning({
      message: '收到敏感内容',
      description: `联系人 ${data.contact.name} 发送了敏感内容。`,
      placement: 'topRight',
      onClick: () => {
        // 点击通知导航到该聊天
        navigate(`/chat/${data.contact.id}`);
      }
    });
  }, [navigate]);

  // 连接WebSocket
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      socketService.connectSocket(token);
      
      // 监听通知事件
      socketService.onEvent('notification', (notification) => {
        handleNotification(notification);
      });
      
      // 监听敏感内容事件
      socketService.onEvent('sensitive:content', (data) => {
        if (user?.role === 'admin') {
          showSensitiveContentNotification(data);
        }
      });
      
      return () => {
        socketService.disconnectSocket();
        socketService.offEvent('notification');
        socketService.offEvent('sensitive:content');
      };
    }
  }, [user, showSensitiveContentNotification]);

  // 处理通知
  const handleNotification = (notificationData) => {
    // 添加到通知列表
    setNotifications(prev => [notificationData, ...prev].slice(0, 5));
    
    // 显示通知
    notification.info({
      message: notificationData.title,
      description: notificationData.message,
      placement: 'topRight'
    });
  };

  // 管理员菜单项
  const adminMenuItems = [
    {
      key: 'admin',
      icon: <SettingOutlined />,
      label: '管理功能',
      children: [
        {
          key: 'admin/users',
          icon: <TeamOutlined />,
          label: '用户管理',
          onClick: () => navigate('/admin/users')
        },
        {
          key: 'admin/presets',
          icon: <FileOutlined />,
          label: '预设文件管理',
          onClick: () => navigate('/admin/preset-files')
        },
        {
          key: 'admin/reports',
          icon: <BarChartOutlined />,
          label: '工作报告',
          onClick: () => navigate('/admin/activity-report')
        }
      ]
    }
  ];

  // 用户下拉菜单项
  const userMenuItems = [
    {
      key: '1',
      icon: <UserOutlined />,
      label: '个人资料',
      disabled: true,
      onClick: () => message.info('个人资料功能开发中')
    },
    {
      type: 'divider'
    },
    {
      key: '2',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
      danger: true
    }
  ];

  // 通知菜单项
  const notificationItems = notifications.length > 0 
    ? notifications.map((notification, index) => ({
        key: index,
        label: (
          <div>
            <div style={{ fontWeight: 'bold' }}>{notification.title}</div>
            <div style={{ fontSize: '12px', color: '#999' }}>{notification.message}</div>
          </div>
        )
      }))
    : [{ key: 'empty', label: '暂无通知', disabled: true }];

  // 处理登出
  function handleLogout() {
    logout();
    navigate('/login');
  }

  // 主菜单项定义
  const mainMenuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '首页',
      onClick: () => navigate('/dashboard')
    },
    {
      key: 'connect',
      icon: <LinkOutlined />,
      label: 'WhatsApp连接',
      onClick: () => navigate('/connect')
    },
    {
      key: 'chats',
      icon: <MessageOutlined />,
      label: '聊天',
      children: [
        {
          key: 'all-chats',
          label: '所有聊天',
          onClick: () => navigate('/chats')
        }
      ]
    },
    // CRM功能
    {
      key: 'crm',
      icon: <TeamOutlined />,
      label: 'CRM',
      children: [
        {
          key: 'crm-customers',
          label: '客户管理',
          onClick: () => navigate('/crm/customers')
        }
      ]
    },
    // 仅管理员可见
    ...(user?.role === 'admin' ? adminMenuItems : [])
  ];

  return (
    <Layout className="layout-with-sidebar">
      <Header className="main-header">
        <div className="header-left">
          {collapsed ? (
            <Tooltip title="展开菜单">
              <ArrowLeftOutlined 
                className="trigger"
                onClick={() => setCollapsed(false)}
                style={{ fontSize: 16, color: 'white' }}
              />
            </Tooltip>
          ) : (
            <div className="logo-with-text">
              <WechatOutlined style={{ fontSize: 24, marginRight: 8 }} />
              <Title level={4} style={{ color: 'white', margin: 0 }}>WhatsApp中间平台</Title>
            </div>
          )}
        </div>
        
        {/* 搜索组件 */}
        <div className="header-search">
          <ContactSearch />
        </div>
        
        <div className="header-actions">
          {/* 通知图标 */}
          <Dropdown 
            menu={{ items: notificationItems }} 
            placement="bottomRight" 
            trigger={['click']}
            arrow
          >
            <div onClick={e => e.preventDefault()}>
              <Badge count={notifications.length} size="small">
                <Avatar 
                  className="action-icon"
                  icon={<BellOutlined style={{ fontSize: 20 }} />}
                  size={40}
                />
              </Badge>
            </div>
          </Dropdown>
          
          {/* 消息收件箱 */}
          <div onClick={() => navigate('/inbox')}>
            <Badge dot={true} offset={[-5, 5]}>
              <Avatar 
                className="action-icon"
                icon={<InboxOutlined style={{ fontSize: 20 }} />}
                size={40}
              />
            </Badge>
          </div>
          
          {/* 用户头像和菜单 */}
          <Dropdown 
            menu={{ items: userMenuItems }} 
            placement="bottomRight" 
            trigger={['click']} 
            arrow
          >
            <div className="user-dropdown" onClick={e => e.preventDefault()}>
              <Avatar 
                src={user?.avatar}
                icon={!user?.avatar && <UserOutlined />}
                style={{ backgroundColor: !user?.avatar ? '#1890ff' : undefined }}
                size={40}
              />
              <Space direction="vertical" size={0} className="user-info">
                <Text strong style={{ color: 'white' }}>{user?.fullName || user?.username || '用户'}</Text>
                <Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 12 }}>
                  {user?.role === 'admin' ? '管理员' : '销售人员'}
                </Text>
              </Space>
            </div>
          </Dropdown>
        </div>
      </Header>
      <Layout>
        <Sider
          width={220}
          collapsible
          collapsed={collapsed}
          onCollapse={setCollapsed}
          theme="light"
          className="main-sider"
        >
          <Menu
            mode="inline"
            style={{ height: '100%', borderRight: 0 }}
            selectedKeys={[location.pathname.slice(1)]}
            defaultOpenKeys={['chats', 'admin']}
            className="main-menu"
            items={mainMenuItems}
          />
          
          {/* 底部版本信息 */}
          {!collapsed && (
            <div className="sider-footer">
              <Divider style={{ margin: '12px 0' }} />
              <div style={{ padding: '0 24px', color: '#999', fontSize: 12 }}>
                <div>版本 v1.0.0</div>
                <div>© 2025 WhatsApp中间平台</div>
              </div>
            </div>
          )}
        </Sider>
        <Layout className="site-layout">
          <Content
            className="site-content"
            style={{
              padding: 24,
              margin: 0,
              minHeight: 280,
              background: '#f5f7fa',
              overflow: 'auto',
              height: 'calc(100vh - 64px)',
            }}
          >
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default MainLayout; 